import { getFirstHashString, PUBLIC_PATH } from '@inbiz/utils';
import { createFromIconfontCN } from '@ant-design/icons';
import { version } from '@settings';

export const PortalColors = {
  primary: '#108ee9',
};

//文件大小单位换算函数
export function formatBytes(bytes: number, decimals?: number) {
  if (bytes == 0) return '0 Bytes';
  var k = 1024,
    dm = decimals || 2,
    sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

export function strNull(
  v: string | number | undefined | null,
  defaultValue?: any,
) {
  if (v == undefined || v == null || (typeof v == 'number' && isNaN(v))) {
    return defaultValue || '';
  }
  return v;
}

/**
 * 解析时间格式/Date(time+timezone)/格式的时间和timestamp
 * @param {*} time
 */
export function parseTime(time: any) {
  if (typeof time === 'string') {
    let match = time.match(/^\/\Date\((\d+)\+(\d+)\)\/$/);
    if (match) {
      return new Date(Number(match[1]));
    } else {
      if (isNaN(Number(time))) {
        return new Date(time);
      } else {
        return new Date(Number(time));
      }
    }
  } else if (typeof time === 'number') {
    return new Date(time);
  } else {
    return time;
  }
}

export function timeInterval(str: any, nowStr?: any) {
  let result = null;
  // str = str.replace(/\-/g, '/');
  // let beforeTime = Date.parse(new Date(str));
  let beforeTime = parseTime(str).getTime();
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let month = day * 30;
  let year = month * 12;
  let now;
  if (nowStr) {
    now = new Date(nowStr).getTime();
  } else {
    now = new Date().getTime();
  }

  let diffValue = now - beforeTime;

  if (diffValue < 0) {
    // 交换服务器时间，和服务器修改时间。。
    let tmpTime = now;
    now = beforeTime;
    beforeTime = tmpTime;
  }
  let yearC = diffValue / year;
  let monthC = diffValue / month;
  let weekC = diffValue / (7 * day);
  let dayC = diffValue / day;
  let hourC = diffValue / hour;
  let minC = diffValue / minute;
  if (yearC >= 1) {
    result = `年前|${parseInt(yearC.toString())}`;
  } else if (monthC >= 1) {
    result = `月前|${parseInt(monthC.toString())}`;
  } else if (weekC >= 1) {
    result = `周前|${parseInt(weekC.toString())}`;
  } else if (dayC >= 1) {
    result = `天前|${parseInt(dayC.toString())}`;
  } else if (hourC >= 1) {
    result = `小时前|${parseInt(hourC.toString())}`;
  } else if (minC >= 1) {
    result = `分钟前|${parseInt(minC.toString())}`;
  } else {
    result = `刚刚|`;
  }
  return result;
}

const timeIntervalReg = /^\/Date\((\d+)(\+\d+)?\)\/$/;
export function formatTimeInerval(str: any, nowStr?: any) {
  let matched = (str || '').match(timeIntervalReg);
  if (!matched) return '';
  let parseStr = Number(matched[1]);
  if (isNaN(parseStr)) return '';
  let d = new Date(parseStr);
  return timeInterval(d.getTime(), nowStr);
}

export type BreadType = {
  folderName: string;
  folderId: number;
  to?: string;
  params?: Record<string, any> | null;
};

export const LIBRARIES = {
  enterprise: {
    folderId: 1,
    folderName: 'enterpriseLibrary',
  },
  team: {
    folderId: 7,
    folderName: 'teamLibrary',
  },
  personal: {
    folderId: -1,
    folderName: 'personalLibrary',
  },
};

// 日期加N天
export function getNewDay(dateTemp: any, days: number) {
  let date = new Date(dateTemp);
  date.setDate(date.getDate() + days); // 设置天数 +days
  return date;
}

export function getParents(el: any, parentSelector: any /* optional */) {
  // If no parentSelector defined will bubble up all the way to *document*
  if (parentSelector === undefined) {
    parentSelector = document;
  }

  var parents = [];
  var p = el.parentNode;

  while (p !== parentSelector) {
    var o = p;
    if (o == null) {
      return [];
    }
    parents.push(o);
    p = o.parentNode;
  }
  parents.push(parentSelector); // Push that parentSelector you wanted to stop at
  return parents;
}

export function chooseFile(params: {
  accept: string;
  multiple?: boolean;
  capture?: 'camera';
}) {
  return new Promise((resolve) => {
    let uploadInput: any = document.createElement('input');
    uploadInput.setAttribute('type', 'file');
    uploadInput.setAttribute('accept', params.accept);
    if (params.capture) {
      uploadInput.setAttribute('capture', params.capture);
    }
    if (params.multiple == true) {
      uploadInput.setAttribute('multiple', 'true');
    }
    uploadInput.style.display = 'none';
    const onFileInputChange = function (e: any) {
      let files: File[] = e.target.files;
      uploadInput.removeEventListener('change', onFileInputChange);
      setTimeout(() => {
        uploadInput.remove();
        uploadInput = null;
      }, 0);
      resolve(files);
    };
    uploadInput.removeEventListener('change', onFileInputChange);
    uploadInput.addEventListener('change', onFileInputChange);
    document.body.appendChild(uploadInput);
    setTimeout(() => {
      uploadInput.click();
    }, 0);
  });
}

export function getPageUrl(url: string) {
  return `/${getFirstHashString()}${url}`;
}
